# -*- coding: utf-8 -*-
from __future__ import unicode_literals

# Create your views here.
from django.shortcuts import render, HttpResponse
from app import models


# Create your views here.

def hello(request):
    return HttpResponse("这个是app应用")


def add_book(request):
    books = models.Book.objects.create(title="如来神掌", price=200, publish="功夫出版社", pub_date="2010-10-10")
    print(books, type(books))  # Book object (18)
    return HttpResponse("<p>数据添加成功！</p>")


def find_book(request):
    books = models.Book.objects.all()
    print(books, type(books))  # QuerySet类型，类似于list，访问 url 时数据显示在命令行窗口中。
    return HttpResponse("<p>查找成功！</p>")


def order_book(request):
    books = models.Book.objects.order_by("price")  # 查询所有，按照价格升序排列
    booksOrder = models.Book.objects.order_by("-price")  # 查询所有，按照价格降序排列
    print(books)
    print("\n")
    print(booksOrder)
    return HttpResponse("<p>查找成功！</p>")


def reverse_book(request):
    # 按照价格升序排列：降序再反转
    books = models.Book.objects.order_by("-price").reverse()
    return HttpResponse("<p>查找成功！</p>")


def count_book(request):
    books = models.Book.objects.count()  # 查询所有数据的数量
    books = models.Book.objects.filter(price=200).count()  # 查询符合条件数据的数量
    return HttpResponse("<p>查找成功！</p>")


def exists_book(request):
    books = models.Book.objects.exists()
    # 报错，判断的数据类型只能为QuerySet类型数据，不能为整型
    books = models.Book.objects.count().exists()
    # 报错，判断的数据类型只能为QuerySet类型数据，不能为模型类对象
    books = models.Book.objects.first().exists()
    return HttpResponse("<p>查找成功！</p>")


# values() 方法用于查询部分字段的数据。
def values_book(request):
    # 查询所有的id字段和price字段的数据
    books = models.Book.objects.values("pk", "price")
    print(books[0]["price"], type(books))  # 得到的是第一条记录的price字段的数据
    return HttpResponse("<p>查找成功！</p>")


def exclude_book(request):
    books = models.Book.objects.exclude(pk=5)
    print(books)
    print("//////////////////////////////////////")
    books = models.Book.objects.exclude(publish='天空八部', price=300)
    print(books, type(books))  # QuerySet类型，类似于list。
    return HttpResponse("<p>查找成功！</p>")


def last_book(request):
    books = models.Book.objects.last()  # 返回所有数据的最后一条数据
    return HttpResponse("<p>查找成功！</p>")


def first_book(request):
    books = models.Book.objects.first()  # 返回所有数据的最后一条数据
    return HttpResponse("<p>查找成功！</p>")


def values_list_book(request):
    # 查询所有的price字段和publish字段的数据
    books = models.Book.objects.values_list("price", "publish")
    print(books)
    print(books[0][0], type(books))  # 得到的是第一条记录的price字段的数据
    return HttpResponse("<p>查找成功！</p>")


def filter_book(request):
    # 查询价格为200或者300的数据
    books = models.Book.objects.filter(price__in=[200, 300])
    # 查询价格大于200的数据
    books = models.Book.objects.filter(price__gt=200)
    # 查询价格大于等于200的数据
    books = models.Book.objects.filter(price__gte=200)
    # 查询价格小于300的数据
    books = models.Book.objects.filter(price__lt=300)
    # 查询价格小于等于300的数据
    books = models.Book.objects.filter(price__lte=300)
    # 查询200 - 300 之间
    books = models.Book.objects.filter(price__range=[200, 300])
    # 区分大小写的包含
    books = models.Book.objects.filter(title__contains="如来")
    # 不区分大小写的包含
    books = models.Book.objects.filter(title__icontains="python")  # 不区分大小写
    # 以指定字符开头，= 号后面为字符串
    books = models.Book.objects.filter(title__startswith="如")
    # __endswith 以指定字符结尾，= 号后面为字符串。
    books = models.Book.objects.filter(title__endswith="如")
    # ateField 数据类型的年份
    books = models.Book.objects.filter(pub_date__year=2008)
    # DateField 数据类型的月份
    books = models.Book.objects.filter(pub_date__month=10)
    # DateField 数据类型的天数
    books = models.Book.objects.filter(pub_date__day=0o1)
    return HttpResponse(books)


# 删除
def del_book(request):
    books = models.Book.objects.filter(pk=8).first().delete()
    books = models.Book.objects.filter(pk__in=[1, 2]).delet
    books = models.Book.objects.delete()  # 报错
    books = models.Book.objects.all().delete()  # 删除成功
    return HttpResponse("<p>查找成功！</p>")


# 更新
def update_book(request):
    # 模型类的对象.属性 = 更改的属性值 模型类的对象.save()
    books = models.Book.objects.filter(pk=7).first()
    books.price = 400
    books.save()
    # 方式二：QuerySet 类型数据.update(字段名=更改的数据)（推荐）
    books = models.Book.objects.filter(pk__in=[7, 8]).update(price=888)
    return HttpResponse(books)


from PIL import Image
import time, os


def upload(request):
    if request.method == "GET":
        return render(request, "upload.html")
    '''执行图片的上传'''
    myfile = request.FILES.get("myfile", None)
    if not myfile:
        return HttpResponse("没有上传文件信息")
    filename = str(time.time()) + "." + myfile.name.split('.').pop()
    ## 打开特定的文件进行二进制的写操作
    destination = open("./static/pics/" + filename, "wb+")
    for chunk in myfile.chunks():  # 分块写入文件
        destination.write(chunk)
    destination.close()

    # 执行图片缩放
    im = Image.open("./static/pics/" + filename)
    # 缩放到75*75(缩放后的宽高比例不变):
    im.thumbnail((75, 75))
    # 把缩放后的图像用jpeg格式保存:
    im.save("./static/pics/s_" + filename, None)
    # 执行图片删除
    # os.remove("./static/pics/"+filename)
    return HttpResponse("上传成功！图片：" + filename)


def testupload(request):
    if request.method == "GET":
        return render(request, "test_upload_paper.html")
    elif request.method == "POST":
        title = request.POST.get("title", "")
        content = request.POST.get("content", "")
        pic = request.FILES.get("pic", "")
        models.ArticleUpload.objects.create(title=title, content=content, pic=pic)
        return HttpResponse("Success!")


from django.core.paginator import Paginator


def pagTest(request, pIndex):
    list1 = models.Book.objects.all()
    p = Paginator(list1, 10)
    if pIndex == '':
        pIndex = '1'
    pIndex = int(pIndex)
    list2 = p.page(pIndex)
    plist = p.page_range
    return render(request, 'pagTest.html', {'list': list2, 'plist': plist, 'pIndex': pIndex})
